import {
  useState,
  useEffect,
  checkIsSupportSoterAuthentication,
  showToast,
  startSoterAuthentication,
  checkIsSoterEnrolledInDevice
} from '@tarojs/taro';
import XList from '../XList';
import { View, Block } from '@tarojs/components';
import XRadio from '../XRadio';

const BioAuth = ({ onAuth }) => {
  const [isReadedBios, setIsReadedBios] = useState(false);
  const [bios, setBios] = useState([]);
  const biosLabel = {
    fingerPrint: '指纹识别',
    facial: '人脸识别',
    speech: '声纹识别'
  };
  useEffect(() => {
    checkIsSupportSoterAuthentication()
      .then(({ supportMode = [] }) => {
        setIsReadedBios(true);
        setBios(supportMode.map((x) => ({ text: biosLabel[x], value: x })));

        if (supportMode.length === 1) {
          onChange({ detail: { value: supportMode[0] } });
        } else if (!supportMode.length) {
          onAuth(-1, '您的设备不支持生物认证');
        }
      })
      .catch(() => {
        if (__wxConfig['envVersion'] === 'develop') {
          onAuth(1, '开发工具强制中认证成功');
          return;
        }
        const msg = '读取设备生物认证失败';
        onAuth(0, msg);
        showToast({ title: msg, icon: 'none' });
      });
  }, []);

  const onAuthCore = ({ type }) => {
    checkIsSoterEnrolledInDevice({ checkAuthMode: type })
      .then((res) => {
        const { isEnrolled, errMsg } = res;
        console.log('检查是否录入生物信息', res);
        if (isEnrolled) {
          startSoterAuthentication({
            requestAuthModes: [type],
            challenge: new Date().getTime() + '',
            authContent: `请使用${biosLabel[type]}解锁`
          })
            .then((res) => {
              console.log('开始生物认证', res);
              onAuth(1, '认证成功');
            })
            .catch((error) => {
              console.error(error);
              const msg = '生物验证失败,' + error.errMsg;
              showToast({ title: msg, icon: 'none' });
              onAuth(0, msg);
            });
        } else {
          onAuth(0, '生物验证失败,没有录入' + biosLabel[type] + '信息');
        }
      })
      .catch((error) => {
        const msg = '生物验证失败,' + error.errMsg;
        showToast({ title: msg, icon: 'none' });
        onAuth(0, msg);
      });
  };

  const onChange = (e) => {
    const value = e.detail.value;
    onAuthCore({ type: value });
  };

  return (
    <XList isCustomize={true}>
      {!isReadedBios ? (
        '正在读取生物认证方式'
      ) : bios.length === 0 ? (
        '您的设备不支持生物认证'
      ) : bios.length === 1 ? (
        <View>正在进行{biosLabel[bios[0]]}认证</View>
      ) : (
        <Block>
          <View>选择生物认证方式：</View>
          <XRadio options={bios} onChange={onChange}></XRadio>
        </Block>
      )}
    </XList>
  );
};
BioAuth.defaultProps = {
  onAuth: null
};
export default BioAuth;
